#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

import libs.common as common
import datetime
import pandas as pd


class BreakPoint(object):

    def __init__(self):
        self.sql_get_stocks = """
        SELECT `date`, `code`, `name`, `quote_change`, `latest_price`,`ups_downs`,`amplitude`, `open`, `high`, `low`, 
                        `quantity_ratio`,`closed`, `volume`, `turnover_rate`, `turnover`, `pe_dynamic`, `pb`
                    FROM stock_data.stock_zh_ah_name WHERE `date` > %s and  `date` < %s
"""
        self.sql_get_all_stock_code = """SELECT `code` FROM stock_data.stock_zh_ah_name WHERE `date` = %s"""
        self.add_break_point = """insert into stock_data.stock_break_point (`type`,`latest_price`,`period`,`name`,`code`,`run_time`
        ,`from_date`,`to_date`) values(\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')"""

    # 获取新高，新低
    def loop_stocks(self, day):
        day = day * 7 / 5
        # 考虑到周六日非交易
        tmp_now_time = datetime.datetime.now()  # 修改成默认是当日执行 + datetime.timedelta()
        datetime_int_to = tmp_now_time.strftime("%Y%m%d")
        datetime_int_from = (tmp_now_time + datetime.timedelta(days=-day)).strftime("%Y%m%d")

        today_all_stock = pd.read_sql(sql=self.sql_get_all_stock_code, con=common.engine(), params=[datetime_int_to])
        original_data = pd.read_sql(sql=self.sql_get_stocks, con=common.engine(),
                                    params=[datetime_int_from, datetime_int_to])

        for code in today_all_stock['code']:
            print(code)
            try:
                self.is_break(code, day, original_data=original_data, from_date=datetime_int_from,
                              to_date=datetime_int_to)
            except Exception as e:
                print(e)

    def is_break(self, stock_code, day, original_data, from_date, to_date):
        print(stock_code)
        tmp_stock_data = original_data[(original_data['code'] == stock_code)]
        period_high = tmp_stock_data['latest_price'][1:].max()
        today_high = tmp_stock_data.iloc[tmp_stock_data['name'].size - 1]['high']
        name = tmp_stock_data.iloc[0]['name']
        period_low = tmp_stock_data['latest_price'][1:].min()
        today_low = tmp_stock_data.iloc[tmp_stock_data['name'].size - 1]['low']
        today_latest_price = tmp_stock_data.iloc[tmp_stock_data['name'].size - 1]['latest_price']

        if tmp_stock_data is None or tmp_stock_data.empty:
            print('{} tmp_stock_data is None or empty'.format(stock_code))
            return False

        if tmp_stock_data['name'].size < 5:
            return False

        if today_high >= period_high:
            stock_h = [stock_code, name]

            insert_dict = {'type': 'period_high', 'period': day, 'name': name, 'code': stock_code,
                           'run_time': datetime.datetime.now(),
                           'from_date': from_date, 'to_date': to_date}
            insert_sql = self.add_break_point % ('period_high', today_latest_price, day, name, stock_code,
                                                 datetime.datetime.now(), from_date, to_date)

            common.insert(insert_sql)

        if today_low <= period_low:
            stock_h = [stock_code, name]

            insert_dict = {'type': 'period_low', 'period': day, 'name': name, 'code': stock_code,
                           'run_time': datetime.datetime.now(),
                           'from_date': from_date, 'to_date': to_date}
            insert_sql = self.add_break_point % ('period_low', today_latest_price, day, name, stock_code,
                                                 datetime.datetime.now(), from_date, to_date)

            common.insert(insert_sql)

        return True


if __name__ == '__main__':
    break_point = BreakPoint()
    cal_day = 49
    break_point.loop_stocks(cal_day)
    print("Done")
